/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.majc.travelapplication.DB;

import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

/**
 *
 * @author lujoel
 */
@Stateless
public class JPATravelController<T> implements Serializable{
    
    private Class<T> entityClass;
    
    
    @PersistenceContext(unitName= "travel_pu" )
    private EntityManager em;

    public JPATravelController() {
    }
    
    
    public JPATravelController(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void create(T entity) {
        //em = Persistence.createEntityManagerFactory("travel_pu").createEntityManager();
        
        if(em == null){
            System.out.println("em is nullcvvvvvvvvvvvvvvvvvv");
            em = Persistence.createEntityManagerFactory("travel_pu").createEntityManager();
            
        }
        em.persist(entity);
    }

    public void edit(T entity) {
        em.merge(entity);
    }

    public void remove(T entity) {
        em.remove(em.merge(entity));
    }

    public T find(String id) {
        return em.find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return em.createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(em.getCriteriaBuilder().count(rt));
        javax.persistence.Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
    
}

